<?php
$isadmin = 1;
include_once '../../comm/config.php';
include_once '../../comm/Taoapi_Util.php';
include '../../comm/checkpostandget.php';
include '../check.php';

$Util = new Taoapi_Util();

function sel_sql($table, $sel_field, $where, $alert = 0) {
	global $BIAOTOU;
	$sql = "select $sel_field from $BIAOTOU$table where $where";
	if ($alert == 1) {
		echo $sql;
	}
	$query = mysql_query($sql);
	if ($query) {
		while ($row = mysql_fetch_array($query)) {
			if (strpos($sel_field, ",") or $sel_field == "*") {
				$arr = $row;
			} else {
				$arr = $row[$sel_field];
			}
		}
	}
	return $arr;
}

function update_sql($table, $field_arr, $where, $xs, $alert = 0) { //$xs 0表示更新 1表示同加  2表示同减,$alert默认为0,1表示打印sql语句,2表示先执行在打印
	global $BIAOTOU;
	$sql = "";
	foreach ($field_arr as $k => $v) {
		if ($xs == 0) {
			$sql = "`$k`='$v'," . $sql;
		}
		elseif ($xs == 1) {
			$sql = "`$k`=`$k`+'$v'," . $sql;
		}
		elseif ($xs == 2) {
			$sql = "`$k`=`$k`-'$v'," . $sql;
		}
	}
	$sql = substr($sql, 0, strlen($sql) - 1);
	$sql = "update $BIAOTOU$table set $sql where $where;";
	if ($alert == 0) {
		mysql_query($sql);
	}
	elseif ($alert == 1) {
		echo $sql;
	}
	elseif ($alert == 2) {
		mysql_query($sql);
		echo $sql;
	}
}

function insert_one_sql($table, $field_arr, $alert = 0) {
	global $BIAOTOU;
	$field = "";
	$values = "";
	foreach ($field_arr as $k => $v) {
		$field = "`" . $k . "`," . $field;
		$values = "'" . $v . "'," . $values;
	}
	$field = substr($field, 0, strlen($field) - 1);
	$values = substr($values, 0, strlen($values) - 1);
	$sql = "insert into $BIAOTOU$table($field) values ($values);";
	$query = mysql_query($sql);
	if($query==''){echo mysql_error();exit;}
	if ($alert == 0) {
		if ($query)
			return mysql_insert_id();
		else
			return mysql_error();
	}
	elseif ($alert == 1) {
		echo $sql;
	}
	elseif ($alert == 2) {
		echo $sql;
		if ($query)
			return 1;
		else
			return mysql_error();
	}
}

function inc_fanli($ddusername, $fxje, $tgje, $order_code, $merchant_id) {
	if (JIFENOPEN == 1 && JIFENBL > 0) {
		$jifen = round($fxje * JIFENBL);
		if ($jifen > 0) {
			$msg_tabao_jifen = $jifen . "积分！";
		}
	} else {
		$jifen = 0;
	}

	$field_arr = array (
		'money' => $fxje,
		'jifen' => $jifen,
		'dengji' => 1
	);
	update_sql('user', $field_arr, "ddusername='$ddusername'", 1); //增加会员金额,积分和等级

	//用户消息
	$title = '您获得了新的商城交易返现！';
	$trade_id = $order_code;
	$msg_tabao = "您获得了新的交易返现，" . $merchant_id . "商城订单号" . $order_code . "返现金额" . $fxje . '！' . $msg_tabao_jifen;
	$filed_arr = array (
		'title' => $title,
		'content' => $msg_tabao,
		'addtime' => date('Y-m-d H:i:s'
	), 'see' => 0, 'ddusername' => $ddusername, 'senduser' => '网站客服');
	insert_one_sql("msg", $filed_arr);

	//用户明细
	$shijian = "商城交易返现";
	$memo = $merchant_id . "交易号$order_code";
	$filed_arr = array (
		'ddusername' => $ddusername,
		'shijian' => $shijian,
		'addtime' => date('Y-m-d H:i:s'
	), 'je' => $fxje, 'jifen' => $jifen, 'memo' => $memo);
	insert_one_sql("mingxi", $filed_arr);

	//求推荐人
	$tjrid = sel_sql("user", "tjr", "ddusername='$ddusername'");
	if ($tjrid > 0) {
		$tjrname = sel_sql("user", "ddusername", "Id='$tjrid'");
		//增加推荐人佣金
		$field_arr = array (
			'money' => $tgje
		);
		update_sql("user", $field_arr, "Id='$tjrid'", 1);

		//用户消息
		$title = '您获得了新的推广佣金！';
		$msg_taobaotuiguang = "您获得了新的推广佣金" . $tgje;
		$filed_arr = array (
			'title' => $title,
			'content' => $msg_taobaotuiguang,
			'addtime' => date('Y-m-d H:i:s'
		), 'see' => 0, 'ddusername' => $tjrname, 'senduser' => '网站客服');
		insert_one_sql("msg", $filed_arr);

		//用户明细
		$shijian = "推广佣金";
		$memo = "交易人$ddusername";
		$filed_arr = array (
			'ddusername' => $tjrname,
			'shijian' => $shijian,
			'addtime' => date('Y-m-d H:i:s'
		), 'je' => $tgje, 'memo' => $memo);
		insert_one_sql("mingxi", $filed_arr);
	}
}

function get_object_vars_final($obj) {
	if (is_object($obj)) {
		$obj = get_object_vars($obj);
	}

	if (is_array($obj)) {
		$n = 0;
		foreach ($obj as $key => $value) {
			if (($key == 'bill_yyyymmdd' or $key == 'u_id') and $n > 0) {
				if (is_object($value))
					$value = '';
			}
			$obj[$key] = get_object_vars_final($value);
			$n++;
		}
	}
	return $obj;
}

function rep($str){
    $re="/[^\d]/";
    return preg_replace($re,"",$str);
}

if ($_GET['daoru']) {

	$pagesize = 200;
	$page = !($_GET['page']) ? '1' : intval($_GET['page']);
	$frmnum = ($page -1) * $pagesize;

	$sday = date('Y-m-d', strtotime(trim($_GET['sday'])));
	$eday = date('Y-m-d', strtotime(trim($_GET['eday'])));
	$step_day = 0;
	$day1 = '+' . $step_day . ' day';
	$step_day++;
	$day = '+' . $step_day . ' day';

	$sday_step_day = date('Y-m-d', strtotime(trim($_GET['sday']) . ' ' . $day1));
	$sday_next = date('Y-m-d', strtotime(trim($_GET['sday']) . ' ' . $day));

	$insert_trade_num = 0;
	$update_trade_num = 0;
	$trade_num = 0;
	$url = 'http://o.yiqifa.com/servlet/queryCpsMultiRow?sid=' . YISID . '&username=' . YINAME . '&privatekey=' . MIYUE . '&ed=' . $sday . '&st=' . $sday_step_day . '&action_id=&order_no=&wid=' . YIWID . '&status=';
	$Util->fetch($url);
	$c = $Util->results;
	if(!strstr($c,'||')){
	    $c='';
	}
	if ($c != '' && $c!=1) {
		$arr_data = preg_split('/[\n\r]+/i', $c);
		$count = count($arr_data);

		$arr_over = 0;
		$over = 0;

		if ($count == 1) {
			$arr_data = array (
				0 => $arr_data
			);
		}

		if ($count > $page * $pagesize) {
			$arr_data = array_slice($arr_data, $frmnum, $pagesize);
			$do_dingda_num = $page * $pagesize;
		} else {
			$arr_data = array_slice($arr_data, $frmnum, $pagesize);
			$do_dingda_num = count($arr_data);
			$arr_over = 1;
		}

		if ($arr_over == 1) {
			if ($sday_step_day > $eday) {
				$over = 1;
			} else {
				if($sday_next<=$eday){
				    $meta = "<meta http-equiv='refresh' content='1;url=mallgetyiqifa.php?sday=" . $sday_next . "&eday=" . $eday . "&step_day=" . $_GET['step_day'] . "&daoru=1' />";
				}
			}
		} else {
			$page++;
			$meta = "<meta http-equiv='refresh' content='1;url=mallgetyiqifa.php?sday=" . $sday . "&eday=" . $eday . "&step_day=" . $_GET['step_day'] . "&daoru=1&page=" . $page . "' />";
		}

		foreach ($arr_data as $row) {
			if ($row != '' && !is_array($row)) {
				$arr = explode('||', $row);
				$unique_id = $arr[0];
				$merchant_id = trim(iconv('gbk', 'utf-8', $arr[16]));
				$merchant_id = trim(preg_replace('/cps/i', '', $merchant_id));
				$order_time = $arr[4]?date('Ymd His', strtotime($arr[4])):date('Ymd His');
				$order_code = $arr[5];
				$product_code = trim(iconv('gbk', 'utf-8', $arr[7]));
				if($product_code=='汇总'){
				    $item_count=1;
				}
				else{
				    $item_count = $arr[8];
				}
				$item_price = $arr[9];
				$sales = $item_price * $item_count;
				$u_id = rep($arr[10]) ? rep($arr[10]) : 0;
				$dduser = sel_sql("user", "ddusername,dengji", "Id='$u_id'");
				$ddusername = $dduser['ddusername'];
				$dengji = $dduser['dengji'];
				$status = $arr[11]; //订单状态
				switch ($status) {
					case 'R' :
						$stat_desc = '未核对';
						break;
					case 'A' :
						$stat_desc = '核对有效';
						break;
					case 'F' :
						$stat_desc = '无效订单';
						break;
				}
				$commission = $arr[12];
				$fxje = mall_ck_fxje($arr[12], $dengji); //会员返利金额
				$tgje = round($arr[12] * TGBL, 2); //给会员的推广佣金

				$mall_order = sel_sql("mall_order", "id,stat_desc", "unique_id='$unique_id'", 0); //用数据唯一编号验证该交易是否存在于数据库
				if ($mall_order['id'] == '') { //交易不存在
					$field_arr = array (
						'unique_id' => $unique_id,
						'lm' => 'yiqifa',
						'order_time' => $order_time,
						'product_code' => $product_code,
						'merchant_id' => $merchant_id,
						'u_id' => $u_id,
						'order_code' => $order_code,
						'item_count' => $item_count,
						'item_price' => $item_price,
						'sales' => $sales,
						'commission' => $commission,
						'stat_desc' => $stat_desc,
						'bill_yyyymmdd' => $bill_yyyymmdd,
						'fxje' => $fxje,
						'ddusername' => $ddusername
					);
					if ($stat_desc == '核对有效') {
						$field_arr['qrsj'] = date('Y-m-d H:i:s');
					}
					
					$id = insert_one_sql("mall_order", $field_arr, 0);
					$insert_trade_num++;

					if ($stat_desc == '核对有效') {
						if ($ddusername != '' and $fxje > 0) {
							inc_fanli($ddusername, $fxje, $tgje, $order_code, $merchant_id);
						}
					}
				}
				elseif ($mall_order['id'] > 0 and $mall_order['stat_desc'] == '未核对' and $stat_desc == '核对有效') {
					$field_arr_order = array (
						'stat_desc' => '核对有效',
						'qrsj' => date('Y-m-d H:i:s'), 
						'fxje' => $fxje,
						'commission' => $commission,
						'bill_yyyymmdd' => $bill_yyyymmdd
					);
					update_sql('mall_order', $field_arr_order, "id='" . $mall_order['id'] . "'", 0);
					$tgje = round($commission * TGBL, 2);
					if($fxje>0){
					    inc_fanli($ddusername, $fxje, $tgje, $order_code, $merchant_id);
					}
					$update_trade_num++;
				}
				elseif ($mall_order['id'] > 0 and $mall_order['stat_desc'] == '未核对' and $stat_desc == '无效订单') {
					$field_arr_order = array (
						'stat_desc' => '无效订单',
						'qrsj' => date('Y-m-d H:i:s'
					));
					update_sql('mall_order', $field_arr_order, "id='" . $mall_order['id'] . "'", 0);
					$update_trade_num++;
				}
			}
			$trade_num++;
		}
	}
	else{
	    $update_trade_num=0;
		$insert_trade_num=0;
		$count=0;
		$do_dingda_num=0;
		if($sday_next<=$eday ){
		    $meta = "<meta http-equiv='refresh' content='1;url=mallgetyiqifa.php?sday=" . $sday_next . "&eday=" . $eday . "&step_day=" . $_GET['step_day'] . "&daoru=1' />";
		}
	}
}
admin_log('获取商城订单');
mysql_close();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?=$meta?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>管理中心</title>
<link rel="stylesheet" type="text/css" href="../../js/calendar/calendar-blue.css"/>
<script type="text/javascript" src="../../js/calendar/calendar.js"></script>
<link href="../css/style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.STYLE1 {color: #FF3300}
.STYLE2 {color: #009900}
-->
</style>
</head>

<body topmargin="5" leftmargin="0">
<table width="98%" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td height="282" valign="top"><table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td>
          <table cellspacing="0" width="100%" height="207" style="border:1px  solid #DCEAF7;">
            <tr>
              <td height="30" align="left" bgcolor="E9F2FB" class="bigtext"><strong>&nbsp;<img src="../images/arrow.gif" width="16" height="22" align="absmiddle" /> 获取交商城订单</strong></td>
              </tr>
            <tr>
              <td valign="top"><form method="get" name="form1" action="">
<br />
<br />
<table width="589" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td height="40" colspan="2" class="bigtext"><span class="STYLE2">
      亿起发只能获取最近8天的订单。<a href="addmallorders.php">立刻添加</a></span></td>
    </tr>
    <tr>
    <td width="121" height="40" class="bigtext">时间范围：</td>
    <td width="468" height="40" class="bigtext">
      <input name="sday" type="text" id="sday" size="10" value="<?php echo $sday ?>" />
     到  
     <input name="eday" type="text" id="eday" size="10" value="<?php echo $eday ?>" />
     <span class="STYLE2"> 注意时间格式！！！</span> </td>
     
     <script language="javascript" type="text/javascript">
					 date = new Date();
					 document.getElementById ("sday").value="<?php echo $sday ?>";
					document.getElementById ("eday").value="<?php echo $eday ?>";
					Calendar.setup({
						inputField     :    "sday",
						ifFormat       :    "%Y-%m-%d",
						showsTime      :    true,
						timeFormat     :    "24"
					});
					Calendar.setup({
						inputField     :    "eday",
						ifFormat       :    "%Y-%m-%d",
						showsTime      :    true,
						timeFormat     :    "24"
					});
				 </script>
  </tr>
  <tr>
    <td height="40">&nbsp;</td>
    <td height="40">
    <input type="hidden" name="step_day" value="0" style="width:30px; text-align:center" />
    <input type="submit" name="daoru" value="获取交易记录" size="17"></td>
  </tr>
  <tr>
    <td height="40" colspan="2" class="large-green">
	<?php 
	
	if($update_trade_num+$insert_trade_num>0){echo "插入订单".$insert_trade_num."条，更新订单".$update_trade_num; }
	?>
      <br/>
      <?php if($over==0 && $_GET['daoru']!=''){
       echo $sday.' - '.$sday."，共有订单".$count."条，处理订单".$do_dingda_num."<br/>";
	   ?>
      订单获取中，请勿对网页有任何操作！
	  <?php }elseif($over==1){?>
      订单获取完毕！
      <?php }?>
      </td>
    </tr>
</table>

</form>

</td>
                </tr>
              </table></td>
            </tr>
          </table></td>
        </tr>
      
    </table></td>
  </tr>
</table>
</body>
</html>